<script lang="ts" setup>
import { useSettingsStore } from "@/pinia/stores/settings"
import { useLayoutMode } from "@@/composables/useLayoutMode"
import {ref, watchEffect, nextTick, watch} from "vue";
import axios from "axios";
const { isLeft } = useLayoutMode()
import {useUserStore} from '@/pinia/stores/user'
const userStore = useUserStore()
const settingsStore = useSettingsStore()

// 使用 storeToRefs 将提取的属性保持其响应性
const {
  showTagsView,
  showLogo,
  fixedHeader,
  showFooter,
  showNotify,
  showThemeSwitch,
  showScreenfull,
  showSearchMenu,
  cacheTagsView,
  showWatermark,
  showGreyMode,
  showColorWeakness
} = storeToRefs(settingsStore)

// 非左侧模式时，Header 都是 fixed 布局
watchEffect(() => {
  !isLeft.value && (fixedHeader.value = true)
})
const count = ref(10)
const isLoading = ref(false);
const ransferLabor = ref(false);
const chatList = ref();
const chatLists = ref();
const datas = ref("")
const userinfo = ref('')
const ChatHistory = ref([{"user": userinfo.value, "chat": "欢迎使用大学生创新创业管理系统系统"},
  {"user": userinfo.value, "chat": "您好，我是您的智能助理，很高兴为您服务，您可以直接发送问题向我提问~"},
  {"user": userinfo.value, "chat": "您好有什么能帮到你？"}])

const nsferHistory = ref([{"user": userinfo.value, "artificial": "欢迎使用大学生创新创业管理系统系统"},
  {"user": userinfo.value, "artificial": "您好有什么能帮到你？"}])
let userdata = userStore.userInfo
const isAdmin = () => {
  if (userdata.occupation === 2){
    nsferHistory.value=[]
  }
}
isAdmin();

watch(() => ChatHistory.value.length, () => {
  nextTick(() => {
    if (chatList.value) {
      scrollBottom();
    }
  })
})
watch(() => nsferHistory.value.length, () => {
  nextTick(() => {
    if (chatLists.value) {
      scrollBottoms();
    }
  })
})
const scrollBottom = () => {
  chatList.value? chatList.value.scrollTop = chatList.value.scrollHeight: null;
}
const scrollBottoms = () => {
  chatLists.value? chatLists.value.scrollTop = chatLists.value.scrollHeight: null;
}
const load = (data) => {

}
const customer = reactive({
  userId: '',
  username: '',
  toUserId: '',
  toUsername: '',
  content: '',
  headUrl: userdata.headUrl,
  identity: 1,
})

const handBangd = async () => {
  if (userinfo.value === "") {
    ChatHistory.value.push({
      "user": "",
      "chat": "还有什么问题吗？请输入问题后在提交哦"
    })
    return; // 如果输入框为空，直接返回，不进行后续操作
  }
    isLoading.value = true; // 设置 isLoading 为 true，禁用按钮
    await axios({
      url: `https://api.sizhi.com/chat?appid=3a1db439ec294b069559ac416fe8bb6d&userid=guanhua&spoken=${encodeURIComponent(userinfo.value)}`,
      method: "get",
    }).then(res => {
      datas.value = res.data.data.info.text
      ChatHistory.value.push({"user": userinfo.value, "chat": datas.value})
    }).catch(error => {
      ChatHistory.value.push({
        "user": "",
        "chat": "请求发送失败，请稍后再试"
      })
    }).finally(() => {
      isLoading.value = false; // 无论请求成功还是失败，最后都设置 isLoading 为 false
      userinfo.value = ''; // 清空输入框
      scrollBottom();
    })

}
const handBangds = () => {
  if (userdata.occupation !== 2){
    customer.userId = userdata.id;
    customer.identity = 0;
    customer.username = userdata.username;
    customer.content = userinfo.value;
    ws.value.send(JSON.stringify(customer)); // 发送消息
    nsferHistory.value.push({"user":userinfo.value, "artificial":'' })
  }else {
    customer.toUserId = userdata.id;
    customer.identity = 1;
    customer.toUsername = userdata.username;
    customer.content = userinfo.value;
    ws.value.send(JSON.stringify(customer)); // 发送消息
    nsferHistory.value.push({"user":'', "artificial": userinfo.value })
  }
  userinfo.value = ''; // 清空输入框
}

// 连接ws
const ws = ref(null);
const ljie = () => {
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    return;
  }
  ws.value = new WebSocket(`ws://localhost:8082/customerMessage/${userdata.id}`);
  ws.value.onopen = (event) => {

  };
  ws.value.onerror = (error) => {
    console.error("WebSocket error:", error);
  };
  ws.value.onclose = (event) => {

  };
  ws.value.onmessage = (event) => {
    try {
      const message = JSON.parse(event.data);
      if (message.identity === 0){
        customer.userId = message.userId;
        customer.username= message.username;
        customer.headUrl = message.headUrl;
        nsferHistory.value.push({"user":message.content, "artificial":'' })
      }else {
        customer.toUserId = message.toUserId;
        customer.toUsername = message.toUsername;
        nsferHistory.value.push({"user":'', "artificial": message.content})
      }
      scrollBottoms();
    } catch (error) {
      console.error("消息解析失败:", error);
    }
  };
}
ljie();


</script>
<template>
  <div class="chat-header">
    <div style="height: 40px;width: 100%;text-align: center;padding-top: 20px">{{ ransferLabor? '人工客服' : '智能客服' }}</div>
    <ul v-if="!ransferLabor" infinite-scroll-distance="1" v-infinite-scroll="load" class="infinite-list" style="overflow: auto">
      <div ref="chatList" class="execInfo">
        <div v-for="(item, index) in ChatHistory" :key="index">
          <div v-if="item.user!==''">
            <div class="right-data">
              <div style="margin-top: 15px;font-size: 20px">{{ userdata.username }}</div>
              <div><img :src="userdata.headUrl" style="width: 50px;height: 50px;border-radius: 50%"/></div>
            </div>
            <div class="texts-user">{{ item.user }}
            </div>
          </div>
          <div>
            <div style="display: flex;margin-left: 10px;margin-top: 40px">
              <el-icon :size="35"><Service /></el-icon>
              <div style="margin-top: 5px;margin-left: 10px">小创智能客服</div>
            </div>
            <div class="texts">{{ item.chat }}
            </div>
          </div>
        </div>
      </div>
    </ul>
    <ul v-if="ransferLabor" infinite-scroll-distance="1" v-infinite-scroll="load" class="infinite-list" style="overflow: auto">
      <div v-if="userdata.occupation === 2" ref="chatLists" class="execInfo">
        <div v-for="(item, index) in nsferHistory" :key="index">
          <div>
            <div v-if="item.user!==''" style="display: flex;margin-left: 10px;margin-top: 40px">
              <img :src="customer.headUrl" style="width: 50px;height: 50px;border-radius: 50%"/>
              <div style="margin-top: 5px;margin-left: 10px;">{{customer.username}}为您服务</div>
            </div>
            <div class="texts">{{ item.user }}
            </div>
          </div>
          <div v-if="item.artificial">
            <div class="right-data">
              <div style="margin-top: 15px;font-size: 20px">{{ customer.toUsername }}</div>
              <div><img src="@/assets/customer.png" style="width: 50px;height: 50px;border-radius: 50%"/></div>
            </div>
            <div class="texts-user">{{ item.artificial }}
            </div>
          </div>
        </div>
      </div>
      <div v-else ref="chatLists" class="execInfo">
        <div v-for="(item, index) in nsferHistory" :key="index">
          <div v-if="item.user!==''">
            <div class="right-data">
              <div style="margin-top: 15px;font-size: 20px">{{ userdata.username }}</div>
              <div><img :src="userdata.headUrl" style="width: 50px;height: 50px;border-radius: 50%"/></div>
            </div>
            <div class="texts-user">{{ item.user }}
            </div>
          </div>
          <div>
            <div v-if="item.artificial" style="display: flex;margin-left: 10px;margin-top: 40px">
              <img src="@/assets/customer.png" style="width: 50px;height: 50px;border-radius: 50%"/>
              <div style="margin-top: 5px;margin-left: 10px;">{{userdata.username}}为您服务</div>
            </div>
            <div class="texts">{{ item.artificial }}
            </div>
          </div>
        </div>
      </div>
    </ul>
    <div class="userinfo" style="display: flex">
      <el-input v-model="userinfo" type="textarea" autosize :disabled="isLoading" @change="handBangd" placeholder="有什么问题可以问我哦"/>
      <el-button v-if="!ransferLabor" style="margin-left: 10px" @click="handBangd" :disabled="isLoading || userinfo === ''" type="primary">发送</el-button>
      <el-button v-else style="margin-left: 10px" @click="handBangds" :disabled="userinfo === ''" type="primary">发送</el-button>
      <el-button style="margin-left: 10px" @click="ransferLabor=!ransferLabor" type="danger">{{ ransferLabor?"退出":"转人工" }}</el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import "@@/assets/styles/mixins.scss";

.setting-container {
  padding: 20px;
  .setting-item {
    font-size: 14px;
    color: var(--el-text-color-regular);
    padding: 5px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .setting-name {
      @extend %ellipsis;
    }
  }
  .el-button {
    margin-top: 40px;
    width: 100%;
  }
}

.chat-header {
  position: relative;
  width: 100%;
  height: 94%;
}

.execInfo {
  width: 100%;
  height: 92%;
  font-size: 16px;
  line-height: 33px;
  color: #606266;
  overflow-y: auto;
}

.userinfo {
  margin-left: 10px;
  width: 94%;
}

.infinite-list {
  height: 86%;
  padding: 0;
  margin: 0;
  list-style: none;
}

.infinite-list .infinite-list-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  background: var(--el-color-primary-light-9);
  margin: 10px;
  color: var(--el-color-primary);
}

.infinite-list .infinite-list-item + .list-item {
  margin-top: 10px;
}

.heidde {
  position: absolute;
  width: 790px;
  overscroll-behavior: contain;
  overflow: auto;
  height: 480px;
}

.texts {
  margin-left: 70px;
  display: inline-block;
  max-width: 70%;
}

.right-data {
  margin-right: 10px;
  display: flex;
  justify-content: flex-end;
}

.texts-user {
  margin-right: 60px;
  margin-top: -15px;
  display: inline-block;
  float: right;
  max-width: 60%;
}

</style>
